package com.cf.game.gate.core;

import com.cf.constant.EnumReturnCode;
import com.cf.game.gate.msg.SelfInfoResponse;
import com.cf.game.msg.Response;
import com.cf.game.node.NodeService;
import com.cf.user.core.EnumSessionCode;
import com.cf.user.login.model.UserInfo;
import com.cf.user.login.service.TokenManager;
import com.cf.util.ObjectJsonUtil;
import com.cf.util.SpringBeanUtil;
import io.vertx.core.http.ServerWebSocket;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * boot-awm-WSService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/27 下午 02:33
 */
public class WSService {

    private Map<Long, UserWrapper> users = new ConcurrentHashMap();

    private Map<ServerWebSocket, Long> socketToUser = new ConcurrentHashMap();


    @Autowired
    private NodeService nodeService;

    public UserWrapper checkUser(String loginInfo, ServerWebSocket ws, String listenQueue) {
        Map<String, Object> urlParams = getUrlParams(loginInfo);

        if (urlParams.get(EnumSessionCode.SESSION_TOKEN_CLIENT_KEY.getValue()) != null) {
            String sessionKey = String.valueOf(urlParams.get(EnumSessionCode.SESSION_TOKEN_CLIENT_KEY.getValue()));
            UserInfo userInfo = SpringBeanUtil.getBean(TokenManager.class).userInfo(sessionKey);
            if (userInfo != null) {
                UserWrapper userWrapper = new UserWrapper(userInfo, ws, System.currentTimeMillis());
                users.put(userInfo.getId(), userWrapper);
                socketToUser.put(ws, userInfo.getId());
                nodeService.registerUserWithNode(userInfo.getId(), listenQueue);
                return userWrapper;
            }
        }
        return null;
    }

    public static Map<String, Object> getUrlParams(String param) {
        Map<String, Object> map = new HashMap<String, Object>(0);
        if (StringUtils.isBlank(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                map.put(p[0], p[1]);
            }
        }
        return map;
    }


    public void logout(ServerWebSocket webSocket) {
        Long userId = socketToUser.remove(webSocket);
        if (userId != null) {
            users.remove(userId);
        }
        nodeService.logout(userId);
    }

    public void deliveryMessage(long userId, String msg) {
        UserWrapper userWrapper = users.get(userId);
        if (userWrapper != null) {
            userWrapper.getWebSocket().writeFinalTextFrame(msg);
        }
    }

    public void selfInfo(ServerWebSocket ws) {
        Long userId = socketToUser.get(ws);
        if (userId != null) {
            UserWrapper userWrapper = users.get(userId);
            if (userWrapper != null) {
                SelfInfoResponse selfInfoResponse = new SelfInfoResponse(userWrapper.getUserInfo());
                userWrapper.getWebSocket().writeFinalTextFrame(ObjectJsonUtil.toString(Response.instance(userId, EnumReturnCode.SUCCESS.getCode(), ObjectJsonUtil.toString(selfInfoResponse))));
            }
        }
    }
    
}
